//
//  MTCreateClubRedpacketController.swift
//  MT
//
//  Created by ooops on 2020/5/15.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import Eureka
import YPNavigationBarTransition
import MTCategory

extension MTCreateClubRedpacketController: MTRedpacketFooterViewDelegate {
    func didClick(commitButton: UIButton) {
        tappedDone()
    }
}

extension MTCreateClubRedpacketController {
    
    override public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 3 ? 200 : 11
    }
    
    override public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
}

public class MTCreateClubRedpacketController : BaseFormViewController, TypedRowControllerType {

    public var row: RowOf<Dictionary<String, String>>!
    public var onDismissCallback: ((UIViewController) -> ())?

    convenience init(_ callback: ((UIViewController) -> ())?){
        self.init()
        onDismissCallback = callback
    }
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "俱乐部红包"
        createTable()
        bindValue()
        _back()
    }
    
    private func _back() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back"), style: .done, target: self, action: #selector(_pop))
    }
    
    @objc func _pop() {
        //recheckPacketValue()
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            self.showValidationMsg(msgs: validationErrors)
            return
        }
        let values = self.form.values()
        
        guard let s = values[clubDateKey] as? Date else {
            MBProgressHUD_JChat.show(text: "请选择红包发送时间", view: self.view)
            return
        }
        
        var requestParam: [String : String] = [clubRAmountKey: "", clubRCountKey: "", clubDateKey: "",]
        
        if let amout = values[clubRAmountKey] as? String {
            requestParam.updateValue(amout, forKey: clubRAmountKey)
        }
        
        if let count = values[clubRCountKey] as? String {
            requestParam.updateValue(count, forKey: clubRCountKey)
        }
        
        if let date = values[clubDateKey] as? Date{
            let dateString = DateManager.string(date: date, format: "HH:mm")
            requestParam.updateValue(dateString, forKey: clubDateKey)
        }
        
        row.value = requestParam
        onDismissCallback?(self)
    }
    
    private func recheckPacketValue() {
        
        guard let _ = row.value?[clubRAmountKey] else {
            MBProgressHUD_JChat.show(text: "请设置总金额", view: self.view)
            return
        }
        
        guard let _ = row.value?[clubRCountKey] else {
            MBProgressHUD_JChat.show(text: "请设置红包个数", view: self.view)
            return
        }
        
        guard let _ = row.value?[clubDateKey] else {
            MBProgressHUD_JChat.show(text: "请设置发送时间", view: self.view)
            return
        }
        self.pop()
    }
    
    private func bindValue() {
        //var requestParam: [String : String] = [clubRAmountKey: "", clubRCountKey: "", clubDateKey: "",]
        if let clubRAmount = row.value?[clubRAmountKey] {
            self.setValue(value: clubRAmount, forTag: clubRAmountKey)
        }
        
        if let clubRCount = row.value?[clubRCountKey] {
            self.setValue(value: clubRCount, forTag: clubRCountKey)
        }
        
        if let clubDate = row.value?[clubDateKey] {
            self.setValue(value: clubDate, forTag: clubDateKey)
        }
    }
    
    lazy var footerView: MTRedpacketFooterView = {
        let c = MTRedpacketFooterView()
        c.delegate = self
        return c
    }()
    
    /// 赋值
    /// - Parameters:
    ///   - value:
    ///   - tag:
    private func setValue(value: String, forTag tag: String) {
        switch tag {
        case clubRAmountKey:
            if let row: MTRedpacketTextFieldRow = self.form.rowBy(tag: tag) as? MTRedpacketTextFieldRow {
                //row.reload()
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    cell.height = { return 64 }
                }
            }
        case clubRCountKey:
            if let row: MTRedpacketTextFieldRow = self.form.rowBy(tag: tag) as? MTRedpacketTextFieldRow {
                row.value = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    cell.height = { return 64 }
                }
            }
        case clubDateKey:
            if let row: MTRedpacketDate = self.form.rowBy(tag: tag) as? MTRedpacketDate {
                let dateformatter = DateFormatter()
                dateformatter.locale = Locale(identifier: "zh_CN")
                dateformatter.dateFormat = "HH:mm"
                let date = dateformatter.date(from: value)!
                row.value = date
                row.reload()
                row.cellUpdate { (cell, row) in

                    cell.height = { return 64 }
                }
            }
        default:
            break
        }
    }
    
    private func createTable() {
        
        let section = Section()
        form +++ section
            <<< MTRedpacketTextFieldRow(){ row in
                row.cell.tipText = "总金额"
                row.cell.setupAccessoryView(text: "元", image: nil)
                row.cell.placeholder = "0.00"
                row.cell.height = { return 64}
                row.cell.keyboardType = .decimalPad
                row.tag = clubRAmountKey
                row.add(rule: MTClubRAmountRule())
            }.onChange({ (row) in
                self.change()
            })
        
        let section1 = Section()
        form +++ section1
                <<< MTRedpacketTextFieldRow(){ row in
                    row.cell.tipText = "红包个数"
                    row.cell.setupAccessoryView(text: "个", image: nil)
                    row.cell.placeholder = "请填写个数"
                    row.cell.height = { return 64}
                    row.cell.keyboardType = .numberPad
                    row.tag = clubRCountKey
                    row.add(rule: MTClubRCountRule())
                    //row.updateCell()
                }.onChange({ (row) in
                    //self.validatorDataDictionary()
                    self.change()
                })
        let section2 = Section()
        form +++ section2
           <<< MTRedpacketDate() { row in
                row.cell.tipText = "每日发送时间"
                row.cell.setupAccessoryView(text: nil, image: nil)
                row.cell.placeholder = "选择时间"
                row.cell.height = { return 64}
                let formatter = DateFormatter()
                formatter.locale = .current
                formatter.dateFormat = "HH时mm分"
                row.dateFormatter = formatter
                //row.cell.keyboardType = .numberPad
                row.tag = clubDateKey
//                row.add(rule: MTClubRDateRule())
                //row.updateCell()
            }.onChange({ (row) in
                //self.validatorDataDictionary()
                self.change()
            })
        
        form +++
        Section() {
            let provider: HeaderFooterProvider<MTRedpacketFooterView> = HeaderFooterProvider<MTRedpacketFooterView>.callback { () -> MTRedpacketFooterView in
                return self.footerView
            }
            var header = HeaderFooterView<MTRedpacketFooterView>.init(provider)
                header.onSetupView = { (view, section) -> () in
                header.height = { return 200 }
            }
            $0.header = header
        }
        
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
    }
    
    private func change() {
        let values = self.form.values()
        var nilOrEmptyValueCount = 0
        for(_, v) in values {
            if v == nil {
                nilOrEmptyValueCount = nilOrEmptyValueCount + 1
            }
            
            if let s = v as? String?, s == "" {
                nilOrEmptyValueCount = nilOrEmptyValueCount + 1
            }
        }
        
        footerView.cancommit(can: nilOrEmptyValueCount == 0)
    }

    public override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }


    @objc func tappedDone(){
        let validationErrors: [ValidationError] = self.form.validate()
        if validationErrors.count != 0 {
            self.showValidationMsg(msgs: validationErrors)
            return
        }
        let values = self.form.values()
        
        guard let s = values[clubDateKey] as? Date else {
            MBProgressHUD_JChat.show(text: "请选择红包发送时间", view: self.view)
            return
        }
        
        var requestParam: [String : String] = [clubRAmountKey: "", clubRCountKey: "", clubDateKey: "",]
        
        if let amout = values[clubRAmountKey] as? String {
            requestParam.updateValue(amout, forKey: clubRAmountKey)
        }
        
        if let count = values[clubRCountKey] as? String {
            requestParam.updateValue(count, forKey: clubRCountKey)
        }
        
        if let date = values[clubDateKey] as? Date{
            let dateString = DateManager.string(date: date, format: "HH:mm")
            requestParam.updateValue(dateString, forKey: clubDateKey)
        }
        
        row.value = requestParam
        onDismissCallback?(self)
    }
    
    private func showValidationMsg(msgs: [ValidationError]) {
        MBProgressHUD_JChat.show(text: msgs.first!.msg, view: self.view)
    }
}

extension MTCreateClubRedpacketController {

    override public func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleOpaque, .showShadowImage]
    }
}
